import random
from rest_framework.response import Response
from django.http import HttpResponse
from django.shortcuts import render
from rest_framework.generics import GenericAPIView
from rest_framework.views import APIView
from rest_framework import status
from meiduo_mall.libs.captcha.captcha import  captcha
from django_redis import get_redis_connection
import logging
#导入第三方包

from .serializers import ImageCodeCheckSerializer
from meiduo_mall.utils.yuntongxun.sms import CCP
from . import constans
from celery_tasks.sms.tasks import send_sms_code
# Create your views here.

logger = logging.getLogger('django')

class ImageCodeView(APIView):
    #图片验证码
    #请求方式　get
    def get(self,request,image_code_id):
        # 接收参数
        # 校验参数　　　序列化器　做了验证内容　可以直接接收参数

        # 生成图片验证码图片 真实值和二进制文本
        text,image=captcha.generate_captcha()
        # 保存真实值 拿到一个链接对象保存验证码
        redis_conn=get_redis_connection('verify_codes')
        # 保存并设置有效期 键名　有效期　数据
        redis_conn.setex("img_%s" % image_code_id, constans.IMAGE_CODE_REDIS_EXPIRES, text)
        # 返回图片
        return HttpResponse(image,content_type='image/jpg')

class SMSCodeView(GenericAPIView):
    #短信验证　传入参数　moble image_code_id  text
    #创建序列化器
    serializer_class = ImageCodeCheckSerializer
    def get(self,request,mobile):
        #检验参数　由序列化完成
        serializer=self.get_serializer(data=request.query_params)
        serializer.is_valid(raise_exception=True)
        #生成短信验证码 随机生成六位数
        sms_code='%06d' % random.randint(0,999999)
        print(sms_code)
        #保存短信验证码　发送记录 从数据库中拿到数据
        redis_conn = get_redis_connection('verify_codes')
        # redis_conn.setex("sms_%s" % mobile, constans.SMS_CODE_REDIS_EXPIRES, sms_code)
        # redis_conn.setex("send_flag_%s" % mobile, constans.SEND_SMS_CODE_INTERVAL, 1)

        #redis　管道 创建pipeline
        pl = redis_conn.pipeline()
        pl.setex("sms_%s" % mobile, constans.SMS_CODE_REDIS_EXPIRES, sms_code)
        pl.setex("send_flag_%s" % mobile, constans.SEND_SMS_CODE_INTERVAL, 1)
        pl.execute()
        # 发送短信
        # try:
        #     ccp=CCP()
        #     expires=constans.SMS_CODE_REDIS_EXPIRES//60
        #     #手机号，短信验证码，有效期，模板ｉｄ
        #     print(expires,mobile,sms_code)
        #     result=ccp.send_template_sms(mobile,[sms_code,expires],constans.SMS_CODE_TEMP_ID)
        # except Exception as e:
        #     logger.error("发送验证码短信[异常][ mobile: %s, message: %s ]" % (mobile, e))
        #     return  Response({'message':'failed',status:status.HTTP_500_INTERNAL_SERVER_ERROR})
        # else:
        #     if result == 0:
        #         logger.info("发送验证码短信[正常][ mobile: %s ]" % mobile)
        #         return Response({'message':'OK'})
        #     else:
        #         logger.warning("发送验证码短信[失败][ mobile: %s ]" % mobile)
        #         return Response({'message': 'failed', status: status.HTTP_500_INTERNAL_SERVER_ERROR})


        #使用celery发送短信验证码
        expires = constans.SMS_CODE_REDIS_EXPIRES // 60
        send_sms_code.delay(mobile,sms_code,expires,constans.SMS_CODE_TEMP_ID)

        return Response({'message':'OK'})
